package com.example.blog.utils;

import lombok.val;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.UUID;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: Hua YY
 * Date: 2025-01-13
 * Time: 13:18
 */
public class SecurityUtils {
    /**
     * 加密
     * password 用户注册时输入的密码
     * return: 数据库中存储的信息：盐值 + md5(明文+盐值)
     */
    public static String encrypt(String password){//将.....加密
        //生成盐值
        String salt = UUID.randomUUID().toString().replace("-","");
        //对 明文（用户注册输入的密码）+盐值 进行md5加密 =>  md5(明文+盐值)
        String finalPassword = DigestUtils.md5DigestAsHex((password+salt).getBytes());
        return salt+finalPassword;
    }

    /**
     * 验证密码
     * @param inputPassword 用户登录时输入的密码
     * @param sqlPassword 数据库中password字段存储的信息  存储的是 盐值+md5(明文+盐值)
     * @return
     */
    public static boolean verify(String inputPassword , String sqlPassword){
        //校验参数
        if (!StringUtils.hasLength(inputPassword)){
            return false;
        }
        if(sqlPassword == null || sqlPassword.length() != 64){
            return false;
        }
        //获取盐值
        String salt = sqlPassword.substring(0,32);
        //根据用户登录时输入的密码和盐值，进行加密
        String finalPassword = DigestUtils.md5DigestAsHex((inputPassword + salt).getBytes());
        return (salt+finalPassword).equals(sqlPassword);
    }

//    public static void main(String[] args) {
//        System.out.println(encrypt("123456"));
//        System.out.println(encrypt("123456"));
//        System.out.println(encrypt("123456"));
//
//        System.out.println(verify("123456", "c50a402f774149d288fb63ba72019b9bc382f11971354fafe707c09651ecc9e5"));
//        System.out.println(verify("123456", "dcf120a55d98493aae9d3b698e7d710645c0f1d1b3cf5cc00a01d3dabcbef128"));
//
//    }
}
